<template>
  <div class="sign-in">
    <Header :title="$t('form.recover.title')" />
    <div class="form-container">
      <a-form ref="formRef" :model="formData">
        <a-form-item name="email" :rules="[
          {
            validator: checkEmail,
            trigger: 'blur',
          },
        ]">
          <a-input size="large" :maxlength="30" :placeholder="$t('form.recover.form.item_1.rules.error_1')" allow-clear
            v-model:value.trim="formData.email">
            <template #prefix><svg class="prefix-icon" width="20" height="20" viewBox="0 0 20 20" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <circle cx="10" cy="6.66667" r="4.16667" stroke="#CCD6DE" stroke-width="1.25" />
                <path
                  d="M17.5 17.5C17.5 16.1739 16.7098 14.9021 15.3033 13.9645C13.8968 13.0268 11.9891 12.5 10 12.5C8.01088 12.5 6.10322 13.0268 4.6967 13.9645C3.29018 14.9021 2.5 16.1739 2.5 17.5"
                  stroke="#CCD6DE" stroke-width="1.25" />
              </svg>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="captcha" :rules="[
          {
            validator: checkCaptcha,
            trigger: 'blur',
          },
        ]">
          <a-input :maxlength="30" size="large" :placeholder="$t('form.code.placeholder')" allow-clear
            v-model:value.trim="formData.captcha">
            <template #prefix><svg width="20" height="20" viewBox="0 0 20 20" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M2.5 6.29075C2.5 5.64791 2.86971 5.06237 3.45011 4.78599L9.28345 2.00821C9.73676 1.79234 10.2632 1.79234 10.7166 2.00821L16.5499 4.78599C17.1303 5.06237 17.5 5.64791 17.5 6.29075V8.79254C17.5 11.536 16.1497 14.1037 13.8893 15.6585L10.4723 18.0088C10.1878 18.2045 9.81218 18.2045 9.52774 18.0088L6.11072 15.6585C3.85033 14.1037 2.5 11.536 2.5 8.79254L2.5 6.29075Z"
                  stroke="#CCD6DE" stroke-width="1.25" />
                <path d="M5.83301 9.58333L9.58301 12.5L14.583 7.5" stroke="#CCD6DE" stroke-width="1.25" />
              </svg>
            </template>
            <template #suffix>
              <div class="code-suffix">
                <div class="send-code" :class="validMobile ? '' : 'disabled'" @click="sendCode" v-if="!tempCaptcha">
                  {{ $t("form.code.get_code") }}
                </div>
                <template v-else>
                  <div class="resend-code" v-if="timeCountDown">
                    {{ timerValue }}s
                  </div>
                  <div :class="validMobile ? '' : 'disabled'" @click="sendCode" v-else>
                    {{ $t("form.code.re_get_code") }}
                  </div>
                </template>
              </div>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="password" :rules="[
          {
            validator: checkPassword,
            trigger: 'blur',
          },
        ]">
          <a-input-password size="large" type="password" :maxlength="30" :placeholder="$t('reg_rules.password')"
            allow-clear v-model:value.trim="formData.password">
            <template #prefix>
              <svg class="prefix-icon" width="20" height="20" viewBox="0 0 20 20" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <rect x="2.5" y="7.5" width="15" height="10" rx="1.66667" stroke="#CCD6DE" stroke-width="1.25" />
                <path
                  d="M13.3333 7.5V5.83333C13.3333 3.99238 11.8409 2.5 9.99996 2.5V2.5C8.15901 2.5 6.66663 3.99238 6.66663 5.83333V7.5"
                  stroke="#CCD6DE" stroke-width="1.25" />
                <path fill-rule="evenodd" clip-rule="evenodd"
                  d="M10.8071 13.9592C11.3196 13.6749 11.6666 13.1283 11.6666 12.5007C11.6666 11.5802 10.9204 10.834 9.99992 10.834C9.07944 10.834 8.33325 11.5802 8.33325 12.5007C8.33325 13.1283 8.68021 13.6749 9.19279 13.9592C9.17568 14.0257 9.16659 14.0955 9.16659 14.1673V15.0007C9.16659 15.4609 9.53968 15.834 9.99992 15.834C10.4602 15.834 10.8333 15.4609 10.8333 15.0007V14.1673C10.8333 14.0955 10.8242 14.0257 10.8071 13.9592Z"
                  fill="#CCD6DE" />
              </svg>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item name="repassword" :rules="[
          {
            validator: checkRePassword,
            trigger: 'blur',
          },
        ]">
          <a-input-password size="large" allow-clear :maxlength="30" type="password"
            v-model:value.trim="formData.repassword" :placeholder="$t('form.recover.form.item_4.rules.error_1')">
            <template #prefix>
              <svg class="prefix-icon" width="20" height="20" viewBox="0 0 20 20" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <rect x="2.5" y="7.5" width="15" height="10" rx="1.66667" stroke="#CCD6DE" stroke-width="1.25" />
                <path
                  d="M13.3333 7.5V5.83333C13.3333 3.99238 11.8409 2.5 9.99996 2.5V2.5C8.15901 2.5 6.66663 3.99238 6.66663 5.83333V7.5"
                  stroke="#CCD6DE" stroke-width="1.25" />
                <path fill-rule="evenodd" clip-rule="evenodd"
                  d="M10.8071 13.9592C11.3196 13.6749 11.6666 13.1283 11.6666 12.5007C11.6666 11.5802 10.9204 10.834 9.99992 10.834C9.07944 10.834 8.33325 11.5802 8.33325 12.5007C8.33325 13.1283 8.68021 13.6749 9.19279 13.9592C9.17568 14.0257 9.16659 14.0955 9.16659 14.1673V15.0007C9.16659 15.4609 9.53968 15.834 9.99992 15.834C10.4602 15.834 10.8333 15.4609 10.8333 15.0007V14.1673C10.8333 14.0955 10.8242 14.0257 10.8071 13.9592Z"
                  fill="#CCD6DE" />
              </svg>
            </template>
          </a-input-password>
        </a-form-item>
      </a-form>
    </div>
    <div class="btns">
      <a-button :class="hasValue ? '' : 'opacity-4'" type="primary" size="large" block @click="Register"
        :loading="isSubmiting">{{ $t("btnText.reset_password") }}</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { message } from "ant-design-vue";
import Header from "./Header.vue";
import type { EmailRecoverPasswordParams } from "../../../types/member";
import { computed, getCurrentInstance, reactive, ref } from "vue";
import { postSendEmailCode, postSendPhoneCode } from "../../../api/api";
import type { Rule } from "ant-design-vue/es/form";
import {
  postEmailRecoverPassword,
  postMobileRecoverPassword,
} from "../../../api/member";
import { useRouter } from "vue-router";
import { RegEmail, RegMobile } from "../../../data/reg";

const router = useRouter();

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const formData = reactive<EmailRecoverPasswordParams & { repassword?: string }>(
  {
    email: "",
    captcha: "",
    password: "",
    repassword: "",
  }
);

const validMobile = ref(false);

const checkEmail = async (_rule: Rule, value: string) => {
  if (!value) {
    validMobile.value = false;
    return Promise.reject($t("form.recover.form.item_1.rules.error_1"));
  }
  if (value.includes("@")) {
    if (!RegEmail.test(value)) {
      validMobile.value = false;
      return Promise.reject($t("reg_rules.email"));
    } else {
      validMobile.value = true;
      return Promise.resolve();
    }
  } else {
    if (!RegMobile.test(value)) {
      validMobile.value = false;
      return Promise.reject($t("reg_rules.mobile"));
    } else {
      validMobile.value = true;
      return Promise.resolve();
    }
  }
};
const checkCaptcha = async (_rule: Rule, value: string) => {
  if (!tempCaptcha.value) {
    return Promise.reject($t("form.code.error_1"));
  }
  if (value != tempCaptcha.value) {
    return Promise.reject($t("form.code.error_2"));
  } else {
    return Promise.resolve();
  }
};
const checkPassword = async (_rule: Rule, value: string) => {
  let reg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{6,}$/;
  if (!value) {
    return Promise.reject($t("form.recover.form.item_3.rules.error_1"));
  }
  if (!reg.test(value)) {
    return Promise.reject($t("reg_rules.password"));
  } else {
    return Promise.resolve();
  }
};
const checkRePassword = async (_rule: Rule, value: string) => {
  let password = formData.password;
  if (!value) {
    return Promise.reject($t("form.recover.form.item_4.rules.error_1"));
  }
  if (value !== password) {
    return Promise.reject($t("form.recover.form.item_4.rules.no_match"));
  } else {
    return Promise.resolve();
  }
};

// 获取验证码
const tempCaptcha = ref("");
const timeCountDown = ref(false);
let timer: any = null;
const timerValue = ref(60);
const decreseNumber = () => {
  if (timer) return;
  timeCountDown.value = true;
  timer = setInterval(() => {
    if (timerValue.value === 0) {
      timerValue.value = 60;
      timeCountDown.value = false;
      clearInterval(timer);
      timer = null;
    }
    timerValue.value--;
  }, 1000);
};
const sendCode = async () => {
  if (!validMobile.value) return;
  // 发送邮箱验证码
  let res;
  if (RegEmail.test(formData.email)) {
    res = await postSendEmailCode({
      email: formData.email!,
      type: "forget_password",
      lang: "cn",
    });
  } else {
    res = await postSendPhoneCode({
      mobile: formData.email!,
      type: "forget_password",
      lang: "cn",
    });
  }
  if (res.code === 200) {
    tempCaptcha.value = res.captcha!;
    message.success($t("form.code.send_code"));
    decreseNumber();
  } else {
    message.error($t('message.error.send_repeat'));
  }
};

const formRef = ref();
const isSubmiting = ref(false);
// 注册
const Register = () => {
  if (!hasValue.value) return;
  formRef.value.validate().then(async () => {
    let res;
    isSubmiting.value = true;
    if (RegEmail.test(formData.email!)) {
      res = await postEmailRecoverPassword(formData);
    } else {
      let params = {
        mobile: formData.email!,
        password: formData.password!,
        captcha: formData.captcha!,
      };
      res = await postMobileRecoverPassword(params);
    }
    isSubmiting.value = false;
    if (res.code === 200) {
      message.success($t("message.changed_success"));
      router.push("/login");
    } else {
      message.error($t("message.changed_error"));
    }
  });
};

// 绑定按钮透明度
const hasValue = computed(() => {
  let flag = false;
  if (formData.email) flag = true;
  if (formData.captcha) flag = true;
  if (formData.password) flag = true;
  if (formData.repassword) flag = true;
  return flag;
});
</script>
<style scoped lang="less">
@import url("./common.less");

.code-suffix {
  font-size: 21px;
  color: #3d88f2;

  &>div {
    cursor: pointer;

    &.disabled {
      color: #ccd6de;
      cursor: not-allowed;
    }
  }

  .resend-code {
    color: #ccd6de;
  }
}
</style>
